package com.suncaper.shop.service;


import com.suncaper.shop.component.Constant;
import com.suncaper.shop.domain.*;
import com.suncaper.shop.mapper.OrderItemMapper;
import com.suncaper.shop.mapper.OrderMapper;
import com.suncaper.shop.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@Service
public class OrderService {

    @Autowired
    OrderMapper orderMapper;

    OrderExample orderExample;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    ProductService productService;

    @Autowired
    ProductMapper productMapper;

    ProductExample productExample;

    public void save(HttpSession session,HttpServletRequest request){

        Cart cart = (Cart) session.getAttribute("cart");
        Collection<CartItem> cartItems= (Collection<CartItem>) session.getAttribute("items");
        User user = (User) session.getAttribute("userInfo");
        if (user == null){
           return; //未登录
        }
        //封装订单对象
        Order order = new Order();
        order.setOid(UUID.randomUUID().toString().substring(0,20));
        order.setOrdertime(new Date());
        order.setTotal(cart.getTotal());
        order.setState(Constant.ORDER_UNPAY);
        order.setUid(user.getId());
        order.setName(user.getUsername());
        order.setPhone(user.getPhone());
        order.setUser(user);
        //订单项列表  遍历购物项列表
        for (CartItem ci:cartItems) {
            //封装成orderItem
            OrderItem orderItem = new OrderItem();
            orderItem.setItemid(UUID.randomUUID().toString().substring(0,20));
            orderItem.setCount(ci.getCount());
            orderItem.setSubtotal(ci.getSubtotal());
            orderItem.setProduct(ci.getProduct());
            orderItem.setPid(ci.getProduct().getPid());
            orderItem.setOid(order.getOid());
            orderItem.setOrder(order);
            //将Item加入到Order的items中
            order.getItems().add(orderItem);
        }
        //保存订单
        orderMapper.insert(order);
        //保存订单项
        for (OrderItem oi:order.getItems()) {
            orderItemMapper.insert(oi);
        }

        session.setAttribute("order",order);
//        生成订单后清空购物车
        session.removeAttribute("cart");
        //请求转发到订单详情页
    }

    //获取对应用户订单页数据
    public boolean orderList(HttpSession session, Integer uid){
        OrderExample  orderExample=new OrderExample();
        orderExample.createCriteria().andUidEqualTo(uid);
        List<Order> orderList = orderMapper.selectByExample(orderExample);
        if(orderList.isEmpty()){
            return false;
        }
        //得到该用户的总订单列表
        session.setAttribute("orderList",orderList);
        //将各个order下的购物项存入对应的集合

        for (Order order: orderList) {
            //得到对应oid的订单项,需要新建一个Example，否则会加上之前的限制条件
            OrderItemExample orderItemExample=new OrderItemExample();
            orderItemExample.createCriteria().andOidEqualTo(order.getOid());
            List<OrderItem> orderItemList = orderItemMapper.selectByExample(orderItemExample);
            //手动封装product
            for (OrderItem oi: orderItemList) {
                Product product = productService.findByPid(oi.getPid());
                oi.setProduct(product);
            }
            session.setAttribute(order.getOid(),orderItemList);
        }
        return true;
    }


    /**
     * 得到oid对应的Order
     * @param oid
     * @param session
     * @return
     */
    public Order getOrder(String oid ,HttpSession session){
        User user = (User) session.getAttribute("userInfo");
        Order order = orderMapper.selectByPrimaryKey(oid);

        List<OrderItem> orderItemList = (List<OrderItem>) session.getAttribute(oid);
        for (OrderItem o: orderItemList) {
            System.out.println(o.getProduct().getPname());
        }
        //封装order的User,product
        order.setItems(orderItemList);
        order.setUser(user);
        return order;
    }

    /**
     * 提交订单
     * @param oid
     * @param order
     */
    public void submitOrder(String oid,Order order,HttpSession session){
        Order order1 = orderMapper.selectByPrimaryKey(oid);
        order1.setState(1);
        order1.setAddress(order.getAddress());
        order1.setPmethod(order.getPmethod());
        this.orderList(session,((User)session.getAttribute("userInfo")).getId());
        List<OrderItem> orderItemList = (List<OrderItem>) session.getAttribute(oid);
        for (OrderItem o: orderItemList) {
            //得到对应数据库中的product
            Product product = productMapper.selectByPrimaryKey(o.getPid());
            product.setStock(product.getStock()-o.getCount());
            product.setSalecount(product.getSalecount()+o.getCount());
            productMapper.updateByPrimaryKey(product);
        }

        orderMapper.updateByPrimaryKey(order1);
    }

    /**
     * 用户删除订单，只是更改订单属性
     * @param oid
     */
    public void deleteByOid(String oid){
        Order order = orderMapper.selectByPrimaryKey(oid);
        order.setState(4);
        orderMapper.updateByPrimaryKey(order);
    }
}
